﻿#include "login.h"
#include "ui_login.h"
#include "mainui.h"
#include "privatechat.h"
#include "filetrans.h"
#include "personinfoui.h"
#include "register.h"
#include "videocall.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    loadConfig();
    setWindowTitle(" ");
    init();//初始化界面上的用户名密码控件,从文件中读取用户名和密码
    ui->label_6->setStyleSheet("background-color:gray;");
    m_sock.connectToHost(QHostAddress(m_ip),m_port);
    connect(&m_sock,&QTcpSocket::readyRead,this,&Widget::readOpt);//直接取数据
    connect(&m_sock,&QTcpSocket::connected,this,[=](){
        ui->label_6->setStyleSheet("background-color:green;");
    });
    m_timer3.start(300);//m_timer3 此定时器为重复连接文件传输sock
    connect(&m_timer3,&QTimer::timeout,this,[=](){
        m_filesock.connectToHost(QHostAddress(m_ip),10087);
    });

    connect(&m_filesock,&QTcpSocket::connected,this,[=](){
        m_timer3.stop();
        ui->label_6->setStyleSheet("background-color:blue;");
    });
    //读取文件
    connect(&m_filesock,&QTcpSocket::readyRead,this,[=](){
        QByteArray ba = m_filesock.readAll();
        if(!control)
        {
            QString str(ba);
            m_filename = str.section('&',0,0);
            m_filesize = str.section('&',1,1).toUInt();
            QString file = QString("E:/%1").arg(m_filename);
            m_file.setFileName(file);
            if(!m_file.open(QIODevice::WriteOnly))
            {
                qDebug()<<"create file fail"<<endl;
            }
            control = true;
        }
        else
        {
            int r = m_file.write(ba);
            m_recvsize += r;
            if(m_recvsize>=m_filesize)
            {
                control = false;
                m_file.close();
                if(m_filename.contains(".png")|m_filename.contains(".jpg")|m_filename.contains(".bmp"))
                {
                    for(auto x:privateChatList)
                    {
                        if(x->getSelfName()==Widget::getInstance().getName())
                        {
                            QString file = QString("E:/%1").arg(m_filename);
                            QString objname = x->getObjName();
                            int i = objname.indexOf('(');
                            objname =objname.replace(")","");
                            objname = objname.mid(i+1);
                            x->addMsgWidget(x->CreateWidgetL_R(1,objname,QPixmap(file)));
                            break;
                        }
                    }
                }
            }
        }
    });

    //初始化播放器
    m_MediaPlayer = new QMediaPlayer;


    //添加系统托盘
    //加载系统托盘使用的图标
    QIcon icon = QIcon(":/res/joker.png");
    //设置图标
    m_trayIcon.setIcon(icon);
    //当鼠标悬浮，显示文字
    m_trayIcon.setToolTip("Joker");
    //显示此托盘
    m_trayIcon.show();
    //为托盘添加菜单项
    m_ac1.setText("打开主界面");
    m_ac2.setText("退出");
    m_menu.addAction(&m_ac1);
    m_menu.addSeparator();
    m_menu.addAction(&m_ac2);
    m_trayIcon.setContextMenu(&m_menu);
    //为两个菜单项添加槽
    connect(&m_ac1,&QAction::triggered,this,[=](){//托盘的显示响应
        if(!control_show)
            show();
        else {
            MainUI::getInstance().show();
        }
    });
    connect(&m_trayIcon,&QSystemTrayIcon::activated,[=](QSystemTrayIcon::ActivationReason reason){//为托盘添加双击显示功能
        if(reason == QSystemTrayIcon::DoubleClick)
        {
            if(!control_show)
                show();
            else {
                MainUI::getInstance().show();
            }
        }
    });
    connect(&m_ac2,&QAction::triggered,this,[=](){//托盘的退出响应
        exit(0);
    });
    //下面实现界面美化
    setWindowFlags(Qt::FramelessWindowHint);//将窗口标题去掉
    QFile file(":/qss/login_qss.qss");
    if(file.open(QIODevice::ReadOnly))
    {
        QString str = file.readAll();
        setStyleSheet(str);
        m_timer.start(50);
        a=100,b=240,c=240,d=100;
    }
    //控制渐变的定时器
    connect(&m_timer,&QTimer::timeout,this,[=](){
        QString qss = QString("background-color: qlineargradient(spread:pad,  x1:0, x2:1, y1:0, y2:1,  stop: 0 rgba(0,%1,%2,255),stop: 1 rgba(0,%3,%4,255));border: none;border-radius: 5px;color: rgb(255, 255, 255);").arg(a).arg(b).arg(c).arg(d);
        ui->label_4->setStyleSheet(qss);
        a++;c--;b--;d++;
        if(a>240)
        {
            a--;b++;c++;d--;
        }
        if(a<100)
        {
            a++,c--,b--,d++;
        }
    });

    //控制自动登录的计时器
    m_timer2.start(500);
    connect(&m_timer2,&QTimer::timeout,this,[=](){
        if(ui->checkBox_2->isChecked())//自动登录被勾选
        {
            on_btn_login_clicked();
        }
    });

    //当所选项(账户)发生变化时  修改对应头像
    connect(this,&Widget::LoadHead,this,&Widget::HandlerLoadHead);

    //为文本框添加图标
    m_ac3.setIcon(QIcon(":/res/joker.png"));
    ui->username->addAction(&m_ac3,QLineEdit::LeadingPosition);//添加到左侧
    m_ac4.setIcon(QIcon(":/res/lock.png"));
    ui->pwd->addAction(&m_ac4,QLineEdit::LeadingPosition);//添加到左侧
    m_ac5.setIcon(QIcon(":/res/keyboard.png"));
    ui->pwd->addAction(&m_ac5,QLineEdit::TrailingPosition);//添加到右侧


}

Widget::~Widget()
{
    //m_sock.close();
    delete ui;
    delete m_mapper;
    m_trayIcon.destroyed();
    if(m_filesock.state()==QAbstractSocket::ConnectedState)
        m_filesock.disconnectFromHost();
    if(m_sock.state()==QAbstractSocket::ConnectedState)
        m_sock.disconnectFromHost();
    exit(0);
}

void Widget::loadConfig()
{
    QFile file(":/1.txt");
    if(false==file.open(QIODevice::ReadOnly))
    {
        QMessageBox::warning(this,"警告","打开文件失败");
    }
    QByteArray ba = file.readAll();
    file.close();
    QString str(ba.toStdString().c_str());
    QStringList list = str.split("\r\n");
    m_ip = list.at(0);
    m_port = list.at(1).toUInt();
    qDebug()<<m_ip<<m_port;
}

Widget &Widget::getInstance()
{
    static Widget w;
    return w;
}

QTcpSocket &Widget::getTcpSocket()
{
    return m_sock;
}

QTcpSocket &Widget::getFileSocket()
{
    return m_filesock;
}

QString Widget::getName()
{
    return m_name;
}

void Widget::mousePressEvent(QMouseEvent *event)
{
    isPressedWidget = true; // 当前鼠标按下的是QWidget而非界面上布局的其它控件
    last = event->globalPos();
}

void Widget::handlerLoginS()
{
    hide();
    QString msg = QString("Joker:%1(%2)\n声音:开启").arg(m_name).arg(OpDb::getInstance().getNickName(m_name));
    m_trayIcon.setToolTip(msg);
    control_show = true;
    m_timer.stop();
    m_timer2.stop();
    QList<userInfo> listU;
    //读取好友信息
    int len;
    m_sock.read((char*)&len,4);
    for(int i=0;i<len;++i)
    {
        userInfo u;
        m_sock.read((char*)&u,sizeof (u));
        listU.append(u);
    }
    //读取群聊信息
    QList<groupinfo> listG;
    m_sock.read((char*)&len,4);
    for(int i=0;i<len;++i)
    {
        groupinfo g;
        m_sock.read((char*)&g,sizeof (g));
        listG.append(g);
    }

    MainUI::getInstance().setNickName(m_name);
    MainUI::getInstance().setHead(m_name);
    MainUI::getInstance().loadFriend(listU);//从第二个上线的人起  这行代码已经将其好友加载到其列表了
    MainUI::getInstance().loadGroup(listG);
    MainUI::getInstance().show();
    m_filesock.write(ui->username->text().toUtf8(),ui->username->text().toUtf8().length()+1);//将登录名发出去
    rememberPwd();//记录用户名密码
    //发送请求离线聊天记录
    PDU* pdu = makePDU(0);
    pdu->msgType = REQUEST_OFFLINELOG;
    Widget::getInstance().getTcpSocket().write((char*)pdu,pdu->maxSize);
    delete pdu;
    pdu = nullptr;
}

void Widget::handlerOnLine()
{
    userInfo u;
    memset(&u,0,sizeof (u));
    m_sock.read((char*)&u,sizeof(u));
    MainUI::getInstance().updateFriendList(u,ONLINE,"");
    for(auto x:groupChatList)
    {
        x->updateGroupPersonList(u.name,1);
    }
}

void Widget::handlerOffLine()
{
    userInfo u;
    memset(&u,0,sizeof (u));
    m_sock.read((char*)&u,sizeof(u));
    MainUI::getInstance().updateFriendList(u,OFF_ONLINE,"");
    for(auto x:groupChatList)
    {
        x->updateGroupPersonList(u.name,0);
    }
}

void Widget::handlerAddFriend()
{
    userInfo u;
    memset(&u,0,sizeof (u));
    m_sock.read((char*)&u,sizeof(u));
    QString nickname = OpDb::getInstance().getNickName(u.name);

    if(QMessageBox::Ok == QMessageBox::information(this,"消息",QString("%1请求添加好友,是否同意?").arg(nickname),QMessageBox::Ok,QMessageBox::No))
    {
        PDU* pdu = makePDU(0);
        pdu->msgType = ADD_FRIEND_S;
        strcpy(pdu->friendId,u.name);
        m_sock.write((char*)pdu,pdu->maxSize);
        userInfo u;

        QString id = Widget::getInstance().getName();
        strcpy(u.name,id.toStdString().c_str());
        //qDebug()<<"nickname:"<<u.name;
        m_sock.write((char*)&u,sizeof (u));
        delete pdu;
        pdu = nullptr;
    }
    else
    {
        PDU* pdu = makePDU(0);
        pdu->msgType = ADD_FRIEND_F;
        m_sock.write((char*)pdu,pdu->maxSize);
        delete pdu;
        pdu = nullptr;
    }
}

void Widget::handlerAddFriend_S()
{
    QMessageBox::information(this,"消息","添加好友成功");
    QList<userInfo> listU;
    int len;
    m_sock.read((char*)&len,4);
    for(int i=0;i<len;++i)
    {
        userInfo u;
        m_sock.read((char*)&u,sizeof (u));
        listU.append(u);
    }
    MainUI::getInstance().loadFriend(listU);
}

void Widget::handlerMsgRecv()
{
    //播放提示音
    m_MediaPlayer->setMedia(QUrl::fromLocalFile("D:\\QTCode5.14\\CClient\\res\\tip.mp3"));
    m_MediaPlayer->setVolume(100);
    m_MediaPlayer->play();

    userInfo u;
    memset(&u,0,sizeof (u));
    m_sock.read((char*)&u,sizeof(u));
    char msg[1024];
    memset(msg,0,1024);
    m_sock.read(msg,1024);
    QString oname(u.pwd);
    for(auto x:privateChatList)
    {
        QString nickname = OpDb::getInstance().getNickName(oname);
        QString text = nickname+"("+oname+")";
        if(text==x->getObjName())
        {
            QWidget* widget = x->CreateWidgetL_R(1,oname,QString(msg));
            x->addMsgWidget(widget);
            //将消息追加到文件
            QString filename = QString("D:\\ChatRecord\\%1-%2.txt").arg(Widget::getInstance().getName()).arg(u.pwd);
            QFile file(filename);
            if(!file.open(QIODevice::ReadWrite|QIODevice::Append))
            {
                QMessageBox::warning(this,"警告","创建文件失败");
                return;
            }
            QDateTime current_date_time = QDateTime::currentDateTime();
            QString current_date;
            current_date = QString(u.pwd) +"&" + current_date_time.toString("yyyy-MM-dd hh:mm::ss");
            current_date+="\r\n";
            file.write(current_date.toStdString().c_str());
            QString Msg(msg);
            Msg = "わ" + Msg + "わ\r\n";
            file.write(Msg.toStdString().c_str());
            file.close();
            userInfo u2;
            memset(&u2,0,sizeof (u2));
            strcpy(u2.name,u.pwd);
            MainUI::getInstance().updateFriendList(u2,-1,msg);
            //让系统托盘显示消息
            m_trayIcon.showMessage("有新消息",oname+":"+QString(msg),QSystemTrayIcon::Information);
            return;
        }
    }

    PrivateChat* privateChat = new PrivateChat;
    QString nickname = OpDb::getInstance().getNickName(u.pwd);
    QString text = nickname+"("+QString(u.pwd)+")";
    privateChat->setObjName(text);
    privateChat->insertFrienNameToList(text);
    privateChat->setSelectFriend(text);
    //将消息更新到列表
    userInfo u2;
    memset(&u2,0,sizeof (u2));
    strcpy(u2.name,u.pwd);
    MainUI::getInstance().updateFriendList(u2,-1,msg);

    //查找有无聊天记录
    QString filename = QString("D:\\ChatRecord\\%1-%2.txt").arg(Widget::getInstance().getName()).arg(QString(u.pwd));
    QFile file(filename);
    if(file.exists())
    {
        if(!file.open(QIODevice::ReadOnly))
        {
            QMessageBox::warning(this,"警告","打开文件失败");
            return;
        }
        char info[1024];
        char info2[1024];
        while(!file.atEnd())
        {
            memset(info,0,1024);
            memset(info2,0,1024);
            file.readLine(info,1024);
            QString msg2="";
            while(1)
            {
                file.readLine(info2,1024);
                msg2 += QString(info2);
                QString content(info2);
                if(content.endsWith("わ\r\n"))
                {
                    break;
                }
            }
            QString msg = QString(info)+"&" + msg2;
            privateChat->restorChatRecord(msg);
        }
        file.close();
    }
    QWidget* widget = privateChat->CreateWidgetL_R(1,oname,QString(msg));
    privateChat->addMsgWidget(widget);
    privateChatList.append(privateChat);

    //将消息追加到文件
    QString filename2 = QString("D:\\ChatRecord\\%1-%2.txt").arg(Widget::getInstance().getName()).arg(u.pwd);
    QFile file2(filename);
    if(!file2.open(QIODevice::ReadWrite|QIODevice::Append))
    {
        QMessageBox::warning(this,"警告","创建文件失败");
        return;
    }
    QDateTime current_date_time = QDateTime::currentDateTime();
    QString current_date;
    current_date = QString(u.pwd) +"&" + current_date_time.toString("yyyy-MM-dd hh:mm::ss");
    current_date+="\r\n";
    file2.write(current_date.toStdString().c_str());
    QString Msg(msg);
    Msg = "わ" + Msg + "わ\r\n";
    file2.write(Msg.toStdString().c_str());
    file2.close();

    //让系统托盘显示消息
    m_trayIcon.showMessage("有新消息",oname+":"+QString(msg),QSystemTrayIcon::Information);

}

void Widget::handlerSecure_Response_S()
{
    bool ok;
    QString pwd = QInputDialog::getText(this,"回答正确","请输入新密码",QLineEdit::Password,0,&ok);
    if(ok && !pwd.isEmpty())
    {
        PDU* pdu = makePDU(0);
        pdu->msgType = RESET_PWD;
        QString username = ui->username->text();
        strcpy(pdu->friendId,username.toStdString().c_str());
        strcpy(pdu->friendId+13,pwd.toStdString().c_str());
        m_sock.write((char*)pdu,pdu->maxSize);
        delete pdu;
        pdu = nullptr;
    }
}

void Widget::handlerFileRequest()
{
    userInfo u;
    memset(&u,0,sizeof (u));
    m_sock.read((char*)&u,sizeof(u));
    QString text = OpDb::getInstance().getNickName(u.pwd);
    if(QMessageBox::Ok == QMessageBox::information(this,"消息",QString("%1向你发送了文件,是否接收?").arg(text),QMessageBox::Ok,QMessageBox::No))
    {
        PDU* pdu = makePDU(0);
        pdu->msgType = FILE_RESPOND_AGREE;
        m_sock.write((char*)pdu,pdu->maxSize);
        m_sock.write((char*)&u,sizeof (u));
        delete pdu;
        pdu = nullptr;
    }
    else
    {
        PDU* pdu = makePDU(0);
        pdu->msgType = FILE_RESPOND_REFUSE;
        m_sock.write((char*)pdu,pdu->maxSize);
        delete pdu;
        pdu = nullptr;
    }
}

void Widget::handlerMove()
{
    userInfo u;
    memset(&u,0,sizeof (u));
    m_sock.read((char*)&u,sizeof(u));
    QString oname(u.pwd);
    for(auto x:privateChatList)
    {
        QString nickname = OpDb::getInstance().getNickName(oname);
        QString text = nickname+"("+oname+")";
        if(text==x->getObjName())
        {
            int i = 6;
            while(i-->0)
            {
                x->move(500,150);
                x->move(600,250);
                x->move(400,150);
                x->move(500,150);
                x->move(600,250);
                x->move(400,150);
            }
            return;
        }
    }


}

void Widget::handlerMediaReuest()
{
    userInfo u;
    memset(&u,0,sizeof (u));
    m_sock.read((char*)&u,sizeof(u));
    QString text = OpDb::getInstance().getNickName(u.pwd);
    if(QMessageBox::Ok == QMessageBox::information(this,"消息",QString("%1向你发送了视频请求,是否同意?").arg(text),QMessageBox::Ok,QMessageBox::No))
    {
        PDU* pdu = makePDU(0);
        pdu->msgType = MEDIA_REQUEST_AGREE;
        m_sock.write((char*)pdu,pdu->maxSize);
        m_sock.write((char*)&u,sizeof (u));
        VideoCall* v = new VideoCall(nullptr,u.pwd);
        v->sendSignalImgCall();
        v->setWindowTitle(QString("正在与%1通话").arg(u.pwd));
        v->show();
        delete pdu;
        pdu = nullptr;
    }
    else
    {
        PDU* pdu = makePDU(0);
        pdu->msgType = FILE_RESPOND_REFUSE;
        m_sock.write((char*)pdu,pdu->maxSize);
        delete pdu;
        pdu = nullptr;
    }
}

void Widget::handlerAgreeMediaReuest()
{
    userInfo u;
    memset(&u,0,sizeof (u));
    m_sock.read((char*)&u,sizeof(u));
    VideoCall* v = new VideoCall(nullptr,u.name);
    v->sendSignalImgCall();
    v->setWindowTitle(QString("正在与%1通话").arg(u.name));
    v->show();
}

void Widget::handlerRefuseMediaReuest()
{
    handlerRefuseMediaReuest();
    userInfo u;
    memset(&u,0,sizeof (u));
    m_sock.read((char*)&u,sizeof(u));
    QString oname(u.pwd);
    for(auto x:privateChatList)
    {
        QString nickname = OpDb::getInstance().getNickName(oname);
        QString text = nickname+"("+oname+")";
        if(text==x->getObjName())
        {
            QWidget* widget = x->CreateWidgetL_R(1,oname,QString("对方拒绝了你的视频请求"));
            x->addMsgWidget(widget);
            break;
        }
    }
}

void Widget::handlerOffLineLog()
{
    QByteArray ba = m_sock.readAll();
    QString msg(ba);
    qDebug()<<msg<<endl;
    QStringList list = msg.split("\r\n");

    for(int i=0;i<list.size()-1;i+=2)
    {
        QStringList list2 = list[i].split("&");
        QString nickname = OpDb::getInstance().getNickName(list2[0]);
        QString text = nickname+"("+list2[0]+")";
        QString info = list[i+1].replace("わ","");
        if(info.contains("addFriend"))
        {
            userInfo u;
            memset(&u,0,sizeof (u));
            if(QMessageBox::Ok == QMessageBox::information(this,"消息",QString("%1请求添加好友,是否同意?").arg(nickname),QMessageBox::Ok,QMessageBox::No))
            {
                PDU* pdu = makePDU(0);
                pdu->msgType = ADD_FRIEND_S;
                strcpy(pdu->friendId,list2[0].toStdString().c_str());
                m_sock.write((char*)pdu,pdu->maxSize);
                QString id = Widget::getInstance().getName();
                strcpy(u.name,id.toStdString().c_str());
                //qDebug()<<"nickname:"<<u.name;
                m_sock.write((char*)&u,sizeof (u));
                delete pdu;
                pdu = nullptr;
            }
            continue;
        }
        //将消息追加到文件
        QString filename = QString("D:\\ChatRecord\\%1-%2.txt").arg(Widget::getInstance().getName()).arg(list2[0]);
        QFile file(filename);
        if(!file.open(QIODevice::ReadWrite|QIODevice::Append))
        {
            QMessageBox::warning(this,"警告","创建文件失败");
            return;
        }
        userInfo u;
        strcpy(u.name,list2[0].toStdString().c_str());
        MainUI::getInstance().updateFriendList(u,-1,info);
        QString current_date;
        current_date = QString(list2[0]) +"&" + list2[1];
        current_date+="\r\n";
        file.write(current_date.toStdString().c_str());
        QString Msg(info);
        Msg = "わ" + Msg + "わ\r\n";
        file.write(Msg.toStdString().c_str());
        file.close();
        break;
    }

}

void Widget::handlerLoadGroupPerson()
{
    QList<userInfo3> list;
    int len;
    m_sock.read((char*)&len,4);
    for(int i=0;i<len;++i)
    {
        userInfo3 u3;
        m_sock.read((char*)&u3,sizeof (u3));
        list.append(u3);
    }
    QString info(list[0].uhead);
    QStringList slist = info.split("&");
    QString gid0 = slist[1];
    for(auto x:groupChatList)
    {
        QString gid = x->getGroupName();
        int i = gid.indexOf('(');
        gid =gid.replace(")","");
        gid = gid.mid(i+1);
        if(gid0==gid)
        {
            x->clearGroupPersonList();
            for(auto x1:list)
            {
                QString info1(x1.uhead);
                QStringList infolist = info1.split("&");
                QString online(x1.uname);
                x->loadGroupPerson(infolist[0],infolist[2],online.toInt());
            }
        }
    }

}

void Widget::handlerGroupMsg(PDU *pdu)
{
    userInfo u0;
    m_sock.read((char*)&u0,sizeof (u0));
    char msg[1024] = {0};
    m_sock.read(msg,1024);
    //将消息更新到群聊列表
    userInfo u;
    strcpy(u.pwd,u0.name);
    MainUI::getInstance().updateGroupList(u,2,msg,pdu->friendId);
    //将消息更新到群聊窗口
    for(auto x:groupChatList)
    {
        if(x->getGroupName()==QString(pdu->friendId))
        {
            QWidget* widget = x->CreateWidgetL_R(1,u.pwd,QString(msg));
            x->addMsgWidget(widget);
            return;
        }
    }
    QGroupChat* gc = new QGroupChat;
    gc->setGroupName(pdu->friendId);
    QWidget* widget = gc->CreateWidgetL_R(1,u.pwd,QString(msg));
    gc->addMsgWidget(widget);
    groupChatList.append(gc);
    PDU* pdu1 = makePDU(0);
    pdu1->msgType = LOAD_GROUP_PERSON;
    QString recvobj = QString(pdu->friendId);
    int i = recvobj.indexOf('(');
    recvobj =recvobj.replace(")","");
    recvobj = recvobj.mid(i+1);
    strcpy(pdu1->friendId,recvobj.toStdString().c_str());
    Widget::getInstance().getTcpSocket().write((char*)pdu1,pdu1->maxSize);
    gc->setGroupNotify(OpDb::getInstance().getGroupNotify(recvobj));
    delete pdu1;
    pdu1=nullptr;
}

void Widget::mouseMoveEvent(QMouseEvent *event)
{
    if (isPressedWidget)
    {
        int dx = event->globalX() - last.x();
        int dy = event->globalY() - last.y();
        last = event->globalPos();
        move(x()+dx, y()+dy);
    }
}

void Widget::mouseReleaseEvent(QMouseEvent *event)
{
    int dx = event->globalX() - last.x();
    int dy = event->globalY() - last.y();
    move(x()+dx, y()+dy);
    isPressedWidget = false; // 鼠标松开时，置为false
}

void Widget::init()//初始化界面上的用户名密码控件,从文件中读取用户名和密码
{
    QDir dir("D://ChatClientInfo");
    if(!dir.exists())
    {
        dir.mkdir("D://ChatClientInfo");
    }
    QFile file("D://ChatClientInfo//cfg.ini");
    int i = 0;
    if(file.open(QIODevice::ReadOnly))
    {
        m_mapper = new QSignalMapper(this);
        m_AccountList = new QListWidget(this);
        m_AccountList->setFocusPolicy(Qt::NoFocus);
        m_AccountList->setItemDelegate(new MyComboxDelegate);
        ui->comboBox->setModel(m_AccountList->model());
        ui->comboBox->setView(m_AccountList);
        while(!file.atEnd())
        {
            char info[50] = {0};
            file.readLine(info,49);
            QString qinfo(info);
            if(qinfo=="\r\n")break;
            QStringList list = qinfo.split("あ");
            m_vecname.append(list[0]);
            m_vecpwd.append(list[1].replace(list[1].length()-2,2,""));
            QHBoxLayout *horLayout = new QHBoxLayout();//水平布局
            QLabel * label_info = new QLabel();
            QString s = OpDb::getInstance().getHeadPath(list[0]);
            label_info->setStyleSheet(QString("border-image: url(%1);border-radius:25px;").arg(s));
            label_info->setFixedSize(50,50);
            QString userinfo = QString("%1\n%2").arg(list[0]).arg(OpDb::getInstance().getNickName(list[0]));
            QLabel * la2 = new QLabel(userinfo);
            QPushButton * b1 = new QPushButton();
            b1->setIcon(QIcon(":/res/delete.png"));
            b1->setFixedSize(50,50);
            b1->setIconSize(QSize(50,50));
            b1->setStyleSheet("background:rgba(200,200,200,0);border-style:solid;");
            connect(b1,SIGNAL(clicked(bool)),m_mapper,SLOT(map()));
            //connect(b1,&QPushButton::clicked,this,&Widget::deleteaccount);
            m_mapper->setMapping(b1,i);
            m_vector.append(i);
            horLayout->addWidget(label_info); //前面头像
            horLayout->addWidget(la2);//中间名字
            horLayout->addWidget(b1);//后面删除按钮
            QWidget *widget =new QWidget(this);
            widget->setLayout(horLayout);
            QListWidgetItem * Listitem = new QListWidgetItem();
            m_AccountList->addItem(Listitem);
            m_AccountList->setItemWidget(Listitem,widget);
            i++;
        }
        connect(m_mapper,QOverload<int>::of(&QSignalMapper::mapped),this,&Widget::deleteaccount);
    }
    file.close();
}

void Widget::rememberPwd()
{

    QDir dir("D://ChatClientInfo");
    if(!dir.exists())
    {
        dir.mkdir("D://ChatClientInfo");
    }

    QFile file("D://ChatClientInfo//cfg.ini");
    //先读取,再写入防止重复

    if(file.open(QIODevice::ReadOnly))
    {
        m_vecname.clear();
        m_vecpwd.clear();
        while(!file.atEnd())
        {
            char buff[50]={0};
            file.readLine(buff,49);
            QString info(buff);
            if(info=="\r\n")break;
            QStringList list = info.split("あ");
            m_vecname.append(list[0]);
            if(list.size()==1)
            {
                m_vecpwd.append("");
                continue;
            }
            m_vecpwd.append(list[1].replace(list[1].length()-2,2,""));
        }
        file.close();
    }

    //再写入
    if(file.open(QIODevice::WriteOnly))
    {
        QString username = ui->username->text();
        QString pwd = ui->pwd->text();
        qDebug()<<username<<":"<<pwd<<endl;
        if(ui->checkBox->isChecked())
        {
            int i=0;
            for(auto x:m_vecname)
            {
                if(x!=username)i++;
            }
            if(i>=m_vecname.size())
            {
                m_vecname.append(username);
                m_vecpwd.append(pwd);
            }
            else
            {
                m_vecpwd[i]=pwd;
            }
        }
        else
        {
            int i=0;
            for(auto x:m_vecname)
            {
                if(x!=username)i++;
            }
            if(i>=m_vecname.size())
            {
                m_vecname.append(username);
                m_vecpwd.append("");
            }
        }
        for(int i=0;i<m_vecname.size();++i)
        {
            QString userinfo = QString("%1あ%2\r\n").arg(m_vecname[i]).arg(m_vecpwd[i]);
            file.write(userinfo.toStdString().c_str());
        }
    }
    file.close();
}

void Widget::deleteaccount(int i)//删除账户
{
    QMessageBox *message = new QMessageBox(QMessageBox::Question,tr("提示"), tr("是否要删除该账号信息\n请注意:当你选择是时,与此账号有关的所有记录都会被删除"), QMessageBox::Yes | QMessageBox::No,this);
    if(QMessageBox::Yes == message->exec())
    {
        m_vecname.removeAt(m_vector.indexOf(i));
        m_vecpwd.removeAt(m_vector.indexOf(i));
        //当前索引是否为删除对象，若是，则使用第一个
        if(m_vector.indexOf(i)==ui->comboBox->currentIndex())
        {
            if(m_vector.length()!=0)
            {
                ui->comboBox->setCurrentIndex(0);
            }
        }
        if(m_vector.length()==0)
        {
            ui->username->setText("");
            ui->pwd->setText("");
            m_AccountList->setItemHidden(m_AccountList->item(0),true);
            return;
        }
        //删除账号信息
        QListWidgetItem * item;
        item = this->m_AccountList->takeItem(m_vector.indexOf(i));
        this->m_AccountList->removeItemWidget(item);
        delete item;
        m_vector.erase(m_vector.begin()+m_vector.indexOf(i));
    }
    //删除配置文件和聊天记录
    QFile file("D://ChatClientInfo//cfg.ini");
    if(file.open(QIODevice::WriteOnly))
    {
        for(int i=0;i<m_vecname.size();++i)
        {
            QString userinfo = QString("%1あ%2\r\n").arg(m_vecname[i]).arg(m_vecpwd[i]);
            file.write(userinfo.toStdString().c_str());
        }
    }

}

void Widget::readOpt()//收到服务器回复后的操作
{
    PDU* pdu = makePDU(0);
    m_sock.read((char*)pdu,pdu->maxSize);
    switch (pdu->msgType) {
    case RES_F:
        QMessageBox::critical(NULL,"提示","注册失败");
        break;
    case RES_S:
        {
            QMessageBox::information(NULL,"提示",QString("注册成功你的账号是:%1").arg(pdu->dataSize));
            QString id = QString("%1").arg(pdu->dataSize);
            ui->username->setText(id);
            delete pdu;
            pdu = nullptr;
        }
        break;
    case LOG_IN_F:
        QMessageBox::critical(NULL,"提示","登陆失败");
        break;
    case LOG_IN_S:
    {
        handlerLoginS();
        break;
    }

    case ONLINE:
    {
        handlerOnLine();
        break;
    }
    case OFF_ONLINE:
    {   
        handlerOffLine();
        break;
    }
    case ADD_FRIEND:
    {
        handlerAddFriend();
        break;
    }
    case ADD_FRIEND_F:
        QMessageBox::information(this,"消息","对方拒绝加好友或者不在线");
        break;
    case ADD_FRIEND_S:
    {
        handlerAddFriend_S();
        break;
    }
    case MSG_RECV:
    {
        handlerMsgRecv();
        break;
    }
    case SECURE_RESPOND_S:
    {
        handlerSecure_Response_S();
        break;
    }
    case SECURE_RESPOND_F:
    {
        QMessageBox::warning(this,"警告","密保回答错误,请重新回答");
        on_btn_find_pwd_clicked();
        break;
    }
    case RESET_PWD_S:
        QMessageBox::information(this,"提示","密码重置成功");
        break;
    case RESET_PWD_F:
        QMessageBox::warning(this,"提示","密码重置失败");
        break;
    case FILE_REQUEST:
    {
        handlerFileRequest();
        break;
    }
    case FILE_RESPOND_AGREE:
    {
        FileTrans::getInstance().setLableContent(1,PrivateChat::getInstance().getFileName());
        emit PrivateChat::getInstance().FileTransSTart();
        break;
    }
    case FIND_INFO://查找个人信息
    {
        break;
    }
    case SEND_MOVE:
    {
        handlerMove();//处理抖动
        break;
    }
    case MEDIA_REQUEST:
    {
        handlerMediaReuest();
        break;
    }
    case MEDIA_REQUEST_AGREE://同意视频请求
    {
        handlerAgreeMediaReuest();
        break;
    }
    case MEDIA_REQUEST_REFUSE://拒绝视频请求
    {
        handlerRefuseMediaReuest();
        break;
    }
    case REQUEST_OFFLINELOG://服务器发来的离线消息
    {
        handlerOffLineLog();
        break;
    }
    case REG_GROUP_S://注册群聊成功
    {
        userInfo u;
        memset(&u,0,sizeof (u));
        QString gid = QString("%1").arg(pdu->dataSize);
        strcpy(u.name,gid.toStdString().c_str());
        strcpy(u.pwd,pdu->friendId);
        QString msg = pdu->data;
        MainUI::getInstance().updateGroupList(u,1,msg);
        delete pdu;
        pdu = nullptr;
        break;
    }
    case LOAD_GROUP_PERSON://加载群成员
    {
        handlerLoadGroupPerson();
        break;
    }
    case GROUP_MSG:
    {
        handlerGroupMsg(pdu);
        break;
    }
    case LOAD_GROUP_RECORD:
    {
        QByteArray qba = m_sock.readAll();
        for(auto x : groupChatList)
        {
            QString str = x->getGroupName();
            if(str.contains(pdu->friendId))
            {
                x->loadGroupChatRecord(qba);
                break;
            }
        }
        break;
    }
    default:
        break;
    }

}

void Widget::HandlerLoadHead(QString uname)
{
    QString headurl = OpDb::getInstance().getHeadPath(uname);
    QString style = QString("min-width:  80px;max-width:  80px;min-height: 80px;max-height: 80px;border-radius: 40px;border-width: 1 1 1 1;border-image: url(%1) 0 0 0 0 stretch strectch;").arg(headurl);
    ui->label_3->setStyleSheet(style);
}


void Widget::on_btn_reg_clicked()//注册
{
    Register* reswin = new Register();
    reswin->show();
}

void Widget::on_btn_login_clicked()//登陆
{
    QString name = ui->username->text();
    QString pwd = ui->pwd->text();
    m_name = name;
    if(name.isEmpty()&&pwd.isEmpty())
    {
        QMessageBox::warning(NULL,"警告","用户名或密码为空");
        return;
    }
    PDU* pdu = makePDU(0);
    pdu->msgType = LOG_IN;
    m_sock.write((char*)pdu,pdu->maxSize);
    userInfo u;
    memset(&u,0,sizeof (u));
    memcpy(u.name,name.toUtf8(),name.toUtf8().length());
    memcpy(u.pwd,pwd.toUtf8(),pwd.toUtf8().length());
    qDebug()<<u.name<<u.pwd;
    m_sock.write((char*)&u,sizeof (u));
    free(pdu);
    pdu=NULL;
}

void Widget::on_btn_min_clicked()
{
    hide();
}

void Widget::on_btn_close_clicked()
{
    exit(0);
}

void Widget::on_btn_find_pwd_clicked()//找回密码
{
    bool ok;
    QString text = QInputDialog::getText(this,"密保问题","你最喜欢的是什么?",QLineEdit::Password,0,&ok);
    if(ok && !text.isEmpty())
    {
        PDU* pdu = makePDU(0);
        pdu->msgType = SECURE_REQUEST;
        QString username = ui->username->text();
        strcpy(pdu->friendId,username.toStdString().c_str());
        strcpy(pdu->friendId+13,text.toStdString().c_str());
        m_sock.write((char*)pdu,pdu->maxSize);
        delete pdu;
        pdu = nullptr;
    }
}

QPixmap Widget::PixmapToRound(const QPixmap &src, const int &radius)//图片椭圆化
{
    if (src.isNull()) {
        return QPixmap();
    }
    QSize size(2*radius, 2*radius);
    //掩码图（黑白色）
    QBitmap mask(size);
    QPainter painter(&mask);
    //Antialiasing：反走样（抗锯齿）
    painter.setRenderHint(QPainter::Antialiasing);
    //SmoothPixmapTransform：用来在对图片进行缩放时启用线性插值算法而不是最邻近算法
    painter.setRenderHint(QPainter::SmoothPixmapTransform);
    //填充矩形
    painter.fillRect(0, 0, size.width(), size.height(), Qt::white);
    //画刷
    painter.setBrush(QColor(0, 0, 0));
    //绘制圆角矩形
    painter.drawRoundedRect(0, 0, size.width(), size.height(), 190, 190);
    //自适应图片
    QPixmap image = src.scaled(size);
    //setMask：创建不规则窗口使用
    image.setMask(mask);
    return image;
}

QList<PrivateChat*>& Widget::getPrivateChatList()
{
    return privateChatList;
}

QList<QGroupChat *> &Widget::getGroupChatList()
{
    return groupChatList;
}


void Widget::on_comboBox_currentIndexChanged(int index)
{
    ui->username->setText(m_vecname.at(index));
    ui->pwd->setText(m_vecpwd.at(index));
    qDebug()<<m_vecname.at(index)<<m_vecpwd.at(index)<<endl;
    emit LoadHead(ui->username->text());
}
